package com.teamwings.modules.page.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.teamwings.common.constant.FormConstant;
import com.teamwings.common.exception.ServiceException;
import com.teamwings.ctrls.entity.DatabaseTableWithColumns;
import com.teamwings.ctrls.entity.OatAppSupervision;
import com.teamwings.ctrls.entity.OatAppUrge;
import com.teamwings.ctrls.service.OatAppSupervisionService;
import com.teamwings.ctrls.service.OatAppUrgeService;
import com.teamwings.enums.ConstData;
import com.teamwings.enums.CtrlTypeEnum;
import com.google.common.collect.Lists;
import com.teamwings.modules.code.entity.FormTableCode;
import com.teamwings.modules.code.service.IFormTableCodeService;
import com.teamwings.common.exception.ResultException;
import com.teamwings.modules.head.entity.FormTableHead;
import com.teamwings.modules.head.service.IFormTableHeadService;
import com.teamwings.modules.oss.entity.OssFile;
import com.teamwings.modules.oss.service.IOssService;
import com.teamwings.modules.page.mapper.PageMapper;
import com.teamwings.modules.page.service.IPageService;
import com.teamwings.modules.page.vo.FileVo;
import com.teamwings.modules.page.vo.FormDataVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * <p>
 * 表单设计服务实现类
 * </p>
 *
 * @author admin
 * @since 2021-05-06
 */
@Service
@Slf4j
public class PageServiceImpl implements IPageService {

    @Autowired
    private IFormTableHeadService formTableHeadService;

    @Autowired
    private IFormTableCodeService formTableCodeService;

    @Autowired
    private IOssService ossService;

    @Autowired
    private PageMapper pageMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    private OatAppSupervisionService supervisionService;
    @Autowired
    private OatAppUrgeService urgeService;

    @Override
    @Cacheable(value = FormConstant.FORM_HEAD_NAME, key = "#formHeadId")
    public String getTableNameById(String formHeadId) {
        return formTableHeadService.getTableNameById(formHeadId);
    }

    @Override
    // 缓存在一些自动更新表单值的组件处理后，不能返回最新的表单值
    //@Cacheable(value = FormConstant.FORM_PAGE_SHOW, key = "#id")
    public Map<String, Object> show(String formId, String id) {
        String tableName = getTableNameById(formId);
        if (StringUtils.isEmpty(formId)) {
            throw new ResultException("formId不能为空");
        }
        if (StringUtils.isEmpty(id)) {
            throw new ResultException("id不能为空");
        }
        return pageMapper.selectOneByFormIdAndId(tableName, id);
    }

    @Override
    @Transactional
    public String add(FormDataVo formDataVo) {
        String formId = formDataVo.getFormId();
        if (StringUtils.isEmpty(formId)) {
            throw new ResultException("formId不能为空");
        }

        // 查询当前的表类型结构
        Map<String, String> typeMap = formTableCodeService.getTypeMap(formId);
        Map<String, Object> formData = formDataVo.getMap();

        // 对组件的限制属性进行判断
        List<String> removeKey = Lists.newArrayList();

        // 存储需要设置文件上传的字段数据
        Map<String, String> uploadMap = new HashMap<>();

        for (String key : formData.keySet()) {
            String type = typeMap.get(key);
            // 需要特殊处理的组件
            if (CtrlTypeEnum.OA_UPLOAD.getName().equals(type)) {
                uploadMap.put(key, String.valueOf(formData.get(key)));
                // 在formData中剔除当前数据
                removeKey.add(key);
            }
        }

        // 这里根据formTableCode表的table_fields字段，剔除掉不必要的字段
        FormTableCode formTableCode = formTableCodeService.getLatestOneByFormId(formId);
        String tableFields = formTableCode.getTableFields();
        // List<String> fields = null;
        // if (StringUtils.isNotEmpty(tableFields)) {
        //     fields = Lists.newArrayList((tableFields + "," + tableFields.toLowerCase()).split(","));
        // } else {
        //     fields = new ArrayList<>();
        // }
        // List<String> finalFields = fields;

        List<String> finalFields = Lists.newArrayList(tableFields.toLowerCase().split(","));

        formDataVo.getMap().forEach((k, v) -> {
            // 过滤掉没有被@FormCtrlScan扫描的组件相关的字段
            if (!finalFields.contains(k.toLowerCase())) {
                System.out.println(String.format("去除不包含的字段 %s", k));
                removeKey.add(k);
            }

            String[] arr = k.split("&");
            if (arr.length != 1) {
                String value = String.valueOf(formDataVo.getMap().get(arr[0]));
                if ("maxLength".equals(arr[1]) && Integer.parseInt(String.valueOf(v)) < value.length()) {
                    throw new ResultException("内容" + value + "超过最大长度");
                }
                removeKey.add(k);
            }
        });

        //检验完后删除 对应的key值
        removeKey.forEach(v -> {
            formDataVo.getMap().remove(v);
        });

        FormTableHead formHead = formTableHeadService.getById(formId);
        String tableName = formHead.getTableName();


        formData.put("FORM_ID", formId);
        String id = String.valueOf(IdWorker.getId());
        formData.put("ID", id);
        formData.put("FORM_VERSION", String.valueOf(formHead.getTableVersion()));
//        Subject subject = SecurityUtils.getSubject();
//        LoginUser sysUser = (LoginUser) subject.getPrincipal();
//        String username = sysUser.getUsername();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        formData.put("FORM_CREATE_BY", sysUser.getUsername());
        formData.put("FORM_UPDATE_BY", sysUser.getUsername());
        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        formData.put("FORM_CREATE_TIME", nowTime);
        formData.put("FORM_UPDATE_TIME", nowTime);
        formData.put("FORM_STATE", ConstData.RECORD_STATE_NOTINIT);

        // 保存到数据
        Map<String, String> t = JSONObject.parseObject(JSON.toJSONString(formData), new TypeReference<Map<String, String>>(){});
        pageMapper.saveByFormId(tableName, t);

        // 保存正文，附件相关代码
        if (MapUtils.isNotEmpty(uploadMap)) {
            // 处理文件上传
            for (String key : uploadMap.keySet()) {
                String value = uploadMap.get(key);
                FileVo fileVo = JSON.parseObject(value, FileVo.class);
                List<String> ossFileIds = fileVo.getFileIds();
                LambdaQueryWrapper<OssFile> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(OssFile::getId, ossFileIds);
                List<OssFile> ossFileList = ossService.list(queryWrapper);
                // 批量设置对应的实例id(ctrlId || tableId)
                for (OssFile ossFile : ossFileList) {
                    ossFile.setTableId(id);
                    ossFile.setFileType(fileVo.getType());
                }

                // 批量更新
                ossService.updateBatchById(ossFileList);
            }
        }
        return id;
    }

    @Override
    public void remove(String formId, String id) {
        if (StringUtils.isEmpty(id)) {
            throw new ResultException("id不能为空");
        }
        if (StringUtils.isEmpty(formId)) {
            throw new ResultException("formId不能为空");
        }
        String tableName = formTableHeadService.getTableNameById(formId);
        log.debug("表单" + tableName + "：删除id为" + id + "的数据");
        pageMapper.deleteByFormIdAndId(tableName, id, ConstData.RECORD_STATE_DELETE);
    }

    // 暂时弃用
    @Override
    public IPage<Map<String, String>> selectPage(Page<Map<String, String>> formDataPage, Wrapper<?> wrapper) {
        return pageMapper.selectPage(formDataPage, wrapper);
    }

    @Override
    public String getTableCodeBy(String formId,Integer version) {
        if (StringUtils.isEmpty(formId)) {
            throw new ResultException("formId不能为空");
        }
        //FormTableCode formTableCode = formTableCodeService.getLatestOneByFormId(formId);
        FormTableCode formTableCode = formTableCodeService.getByFormIdAndVersion(formId,version);
        String tableCode = formTableCode.getTableCode();
        return tableCode;
        // FormVo formVo = VoUtils.newFormVo(tableCode);
        // return formVo;
        // return JSON.parseObject(tableCode, FormVo.class);
    }

    @Override
    public List<Map<String, Object>> selectAll(String tableName, Wrapper<?> wrapper) {
        return pageMapper.selectAll2(tableName, wrapper);
    }

    @Override
    public Boolean repeat(String formId, String id, String field, String value) {
        if (StringUtils.isEmpty(formId)) {
            throw new ResultException("formId不能为空");
        }
        FormTableHead formTableHead = formTableHeadService.getById(formId);
        String tableName = formTableHead.getTableName();


        // 对field进行校验，判断是否存在该字段
        List<String> columnList = pageMapper.getColumnByTableName(tableName);
        if (!columnList.contains(field.toUpperCase(Locale.ROOT))) {
            throw new ServiceException("请设置正确的字段值");
        }

        // field需要校验，否则可能会被sql注入，hasValue方法中的field使用了sql拼接
        Integer integer = pageMapper.hasValue(tableName, id, field, value);
        return integer >= 1;
    }

    @Override
    public DatabaseTableWithColumns getTableWithColumns(String formId) {
        return pageMapper.getTableWithColumns(formId);
    }

    @Override
    @Cacheable(value = FormConstant.FORM_HEAD_CODE, key="#formId")
    public FormTableCode getLatestOneByFormId(String formId) {
        return pageMapper.getLatestOneByFormId(formId);
    }

    @Override
    public Map<String, String> getTypeMap(String formId) {
        return null;
    }


    @Override
    public IPage<Map<String, String>> selectPageByQueryGenerator(String formId, Long page, Long pageSize, QueryWrapper<?> wrapper) {
        if (StringUtils.isEmpty(formId)) {
            throw new ResultException("formId不能为空");
        }
        FormTableHead formTableHead = formTableHeadService.getById(formId);
        if (formTableHead == null) {
            throw new ResultException("找不到对应的数据表");
        }
        String tableName = formTableHead.getTableName();
        Integer tableVersion = formTableHead.getTableVersion();
        wrapper.eq("FORM_VERSION", tableVersion);
        long pageIndex = (page - 1) * pageSize;
        List<Map<String, String>> records = pageMapper.selectRecords(tableName, pageIndex, pageSize, wrapper);

        Integer count = pageMapper.selectCountByTableName(tableName, wrapper);

        // 封装成IPage对象
        IPage<Map<String, String>> dataPage = new Page<>();
        dataPage.setRecords(records);
        dataPage.setSize(pageSize);
        dataPage.setCurrent(page);
        dataPage.setTotal(count);

        return dataPage;
    }

    //    @Cacheable(value = "pagePage", key = "#formId+'_'+#page+'_'+#pageSize")
    @Override
    public IPage<Map<String, String>> selectPageByRecords(String formId, Long page, Long pageSize, QueryWrapper<?> queryWrapper) {
        return this.selectPageByRecordsWithFields(formId, page, pageSize, queryWrapper, null);
    }

    @Override
    public IPage<Map<String, String>> selectPageByRecords(String formId, Long page, Long pageSize, QueryWrapper<?> queryWrapper, Boolean hasFormId) {
        return this.selectPageByRecordsWithFields(formId, page, pageSize, queryWrapper, null, hasFormId);
    }

    /**
     *
     * @param formId
     * @param page
     * @param pageSize
     * @param fields
     * @return
     */
    @Override
    public IPage<Map<String, String>> selectPageByRecordsWithFields(String formId, Long page, Long pageSize,
                                                                    QueryWrapper<?> queryWrapper, String fields) {
        long s = System.currentTimeMillis();
        if (StringUtils.isEmpty(formId)) {
            throw new ResultException("formId不能为空");
        }
        FormTableHead formTableHead = formTableHeadService.getById(formId);
        if (formTableHead == null) {
            throw new ResultException("找不到对应的数据表");
        }
        String tableName = formTableHead.getTableName();
        Integer tableVersion = formTableHead.getTableVersion();
        long pageIndex = (page - 1) * pageSize;

        if (queryWrapper == null) {
            queryWrapper = new QueryWrapper<>();
        }
//        QueryWrapper<?> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("FORM_CREATE_TIME");
        // queryWrapper.eq("FORM_VERSION", tableVersion);
        List<Map<String, String>> records = null;
        if (fields == null || fields.equals("")) {
            records = pageMapper.selectRecords(tableName, pageIndex, pageSize, queryWrapper);
        } else {
            records = pageMapper.selectRecordsFields(tableName, fields, pageIndex, pageSize, queryWrapper);
        }
        Integer count = pageMapper.selectCountByTableName(tableName, queryWrapper);

        // 封装成IPage对象
        IPage<Map<String, String>> dataPage = new Page<>();
        dataPage.setRecords(records);
        dataPage.setSize(pageSize);
        dataPage.setCurrent(page);
        dataPage.setTotal(count);
        long e = System.currentTimeMillis();
        log.info("运行时间：{}", e - s + "ms");
        return dataPage;
    }

    @Override
    public List<Map<String, String>> selectAllRecords(String formId) {
        if (StringUtils.isEmpty(formId)) {
            throw new ResultException("formId不能为空");
        }
        FormTableHead formTableHead = formTableHeadService.getById(formId);
        if (formTableHead == null) {
            throw new ResultException("找不到对应的数据表");
        }
        String tableName = formTableHead.getTableName();
        Integer tableVersion = formTableHead.getTableVersion();

        QueryWrapper<?> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("FORM_VERSION", tableVersion);

        return pageMapper.selectAll(tableName, queryWrapper);
    }

    @Override
    public IPage<Map<String, String>> selectPageByRecordsWithFields(String formId, Long page, Long pageSize, QueryWrapper<?> queryWrapper, String fields, Boolean hasFormId) {
        long s = System.currentTimeMillis();
        if (hasFormId) {
            this.selectPageByRecordsWithFields(formId, page, pageSize, queryWrapper, fields);
        }

        // hasFormId=false时formId为tableName
        long pageIndex = (page - 1) * pageSize;
        if (queryWrapper == null) {
            queryWrapper = new QueryWrapper<>();
        }

        List<Map<String, String>> records = null;

        if (fields == null || fields.equals("")) {
            records = pageMapper.selectRecords(formId, pageIndex, pageSize, queryWrapper);
        } else {
            records = pageMapper.selectRecordsFields(formId, fields, pageIndex, pageSize, queryWrapper);
        }
        Integer count = pageMapper.selectCountByTableName(formId, queryWrapper);

        // 封装成IPage对象
        IPage<Map<String, String>> dataPage = new Page<>();
        dataPage.setRecords(records);
        dataPage.setSize(pageSize);
        dataPage.setCurrent(page);
        dataPage.setTotal(count);
        long e = System.currentTimeMillis();
        log.info("运行时间：{}", e - s + "ms");
        return dataPage;
    }

    @Override
    public void saveByFormId(String tableName, Map<String, String> formData) {
        pageMapper.saveByFormId(tableName, formData);
    }

    @Override
    @Transactional
    public void edit(FormDataVo formDataVo) {
        String formId = formDataVo.getFormId();
        if (StringUtils.isEmpty(formId)) {
            throw new ResultException("formId不能为空");
        }

        // 查询当前的表结构
        Map<String, String> typeMap = formTableCodeService.getTypeMap(formId);
        Map<String, Object> formData = formDataVo.getMap();

        // 存储需要设置文件上传的字段数据
        Map<String, String> uploadMap = new HashMap<>();
        // 需要在执行插入语句时被删除的字段
        ArrayList<String> removeKey = new ArrayList<>();

        for (String key : formData.keySet()) {
            String type = typeMap.get(key);
            // 需要特殊处理的组件
            if (CtrlTypeEnum.OA_UPLOAD.getName().equals(type)) {
                uploadMap.put(key, String.valueOf(formData.get(key)));

                // 在formData中剔除当前数据
                removeKey.add(key);
            }
        }

        // 这里根据formTableCode表的table_fields字段，剔除掉不必要的字段
        FormTableCode formTableCode = formTableCodeService.getLatestOneByFormId(formId);
        String tableFields = formTableCode.getTableFields();
        List<String> fields = null;
        if (StringUtils.isNotEmpty(tableFields)) {
            fields = Lists.newArrayList(tableFields.toLowerCase().split(","));
        } else {
            fields = new ArrayList<>();
        }
        // 避免把id也过滤掉
        fields.add("id");

        List<String> finalFields = fields;
//        formDataVo.getMap().forEach((k, v) -> {
//            k = k.toLowerCase();
//            // 过滤掉没有被@FormCtrlScan扫描的组件相关的字段
//            if (!finalFields.contains(k)) {
//                removeKey.add(k);
//            }
//        });
        formDataVo.getMap().forEach((k, v) -> {
            // 过滤掉没有被@FormCtrlScan扫描的组件相关的字段
            if (!finalFields.contains(k.toLowerCase())) {
                removeKey.add(k);
            }

            String[] arr = k.split("&");
            if (arr.length != 1) {
                String value = String.valueOf(formDataVo.getMap().get(arr[0]));
                if ("maxLength".equals(arr[1]) && Integer.parseInt(String.valueOf(v)) < value.length()) {
                    throw new ResultException("内容" + value + "超过最大长度");
                }
                removeKey.add(k);
            }
        });


        //检验完后删除 对应的key值
        removeKey.forEach(v -> formDataVo.getMap().remove(v));

        // 获取head对象
        FormTableHead formHead = formTableHeadService.getById(formId);

        String id = String.valueOf(formData.get("ID"));
        if (StringUtils.isEmpty(id)) {
            throw new ResultException("id不能为空");
        }
//        formData.remove("ID");
//        formData.put("ID", id);
        formData.put("FORM_VERSION", String.valueOf(formHead.getTableVersion()));
        // todo 此处日后需要设置更新人
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        formData.put("FORM_UPDATE_BY", sysUser.getUsername());
        formData.put("FORM_UPDATE_TIME", new Date().toString());
        String tableName = formHead.getTableName();
        Map<String, String> t = JSONObject.parseObject(JSON.toJSONString(formData), new TypeReference<Map<String, String>>(){});
        pageMapper.updateByFormId(tableName, t);

        // 表单更新成功后进行 督办催办的标题更新
        supervisionService.update(new OatAppSupervision().setTitle(formDataVo.getTheTitle()),
            new LambdaQueryWrapper<OatAppSupervision>().eq(OatAppSupervision::getFormId,id));
        urgeService.update(new OatAppUrge().setTitle(formDataVo.getTheTitle()),
            new LambdaQueryWrapper<OatAppUrge>().eq(OatAppUrge::getFormId,id));


        // 处理文件上传
        if (MapUtils.isNotEmpty(uploadMap)) {
            LambdaQueryWrapper<OssFile> allQueryWrapper = new LambdaQueryWrapper<>();
            allQueryWrapper.eq(OssFile::getTableId, id);
            allQueryWrapper.eq(OssFile::getTableName, tableName);
            // 获取所有数据
            List<OssFile> allData = ossService.list(allQueryWrapper);
            List<String> allIds = allData.stream().map(OssFile::getId).collect(Collectors.toList());

            List<String> tempIds = new ArrayList<>();

            // 处理文件上传
            for (String key : uploadMap.keySet()) {
                String value = uploadMap.get(key);

                FileVo fileVo = JSON.parseObject(value, FileVo.class);
                List<String> ossFileIds = fileVo.getFileIds();

                LambdaQueryWrapper<OssFile> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(OssFile::getId, ossFileIds);
                List<OssFile> ossFileList = ossService.list(queryWrapper);

                // 批量设置对应的实例id(ctrlId || tableId)
                for (OssFile ossFile : ossFileList) {
                    ossFile.setTableId(id);
                    ossFile.setFileType(fileVo.getType());
                }

                // 批量更新
                ossService.updateBatchById(ossFileList);
                tempIds.addAll(ossFileIds);
            }

            // 求差集
            allIds.removeAll(tempIds);

            if (allIds.size() > 0) {
                // 删除对应数据
                LambdaQueryWrapper<OssFile> removeQueryWrapper = new LambdaQueryWrapper<>();
                removeQueryWrapper.in(OssFile::getId, allIds);
                ossService.remove(removeQueryWrapper);
            }
        }
    }


    @Override
    public int update(String tableName, Map<String, String> formData) {
        return pageMapper.updateByFormId(tableName, formData);
    }

    @Override
    public List<Map> executeSql(String sql){
        return pageMapper.executeSql(sql);
    }

    @Override
    public List<FormTableCode> getTableCodeVersionByHeadId(String headId) {
        if (StringUtils.isEmpty(headId)) {
            throw new ResultException("headId不能为空");
        }
        return formTableCodeService.getAllVersionByHeadId(headId);
    }

    @Override
    public List<String> getColumnByTableName(String tableName) {
        return pageMapper.getColumnByTableName(tableName);
    }

    /**
     * 根据sql获取分页数据
     * @param sql
     * @param page
     * @param pageSize
     * @param queryWrapper
     * @param hasWhere
     * @return
     */
    @Override
    public IPage<Map<String, String>> selectRecordsBySql(
            String sql,
            Long page,
            Long pageSize,
            QueryWrapper<?> queryWrapper,
            Boolean hasWhere
    ) {
        long s = System.currentTimeMillis();
        long pageIndex = (page - 1) * pageSize;

        if (queryWrapper == null) {
            queryWrapper = new QueryWrapper<>();
        }

        String sqlSegment = queryWrapper.getSqlSegment();

        List<Map<String, String>> records = pageMapper.selectRecordsBySql(sql, pageIndex, pageSize, queryWrapper, hasWhere);
        Integer count = pageMapper.selectCountBySql(sql, queryWrapper, hasWhere);

        // 封装成IPage对象
        IPage<Map<String, String>> dataPage = new Page<>();
        dataPage.setRecords(records);
        dataPage.setSize(pageSize);
        dataPage.setCurrent(page);
        dataPage.setTotal(count);
        long e = System.currentTimeMillis();
        log.info("运行时间：{}", e - s + "ms");
        return dataPage;
    }

    @Override
    public List<Map<String, Object>> selectBySql(String sql, QueryWrapper<?> queryWrapper, Boolean hasWhere) {
        return pageMapper.selectBySql(sql, queryWrapper, hasWhere);
    }

    @Override
    public JdbcTemplate getJdbcTemplate() {
        return this.jdbcTemplate;
    }

    @Override
    public List<Map<String, Object>> querySql(String sql, Map<String, Object> params) {
        SqlParameterSource parameterSource = new MapSqlParameterSource(params);
//        return namedParameterJdbcTemplate.query(sql, parameterSource, new ResultSetExtractor<List<Map<String, Object>>>() {
//            @Override
//            public List<Map<String, Object>> extractData(ResultSet resultSet) throws SQLException, DataAccessException {
//                return convertList(resultSet);
//            }
//        });
        return namedParameterJdbcTemplate.query(sql, parameterSource, this::convertList);
    }

    @Override
    public String getTableCodeByFormId(String formId) {
        return pageMapper.getTableCodeByFormId(formId);
    }

    @Override
    public List<Map> selectFields(String fields, String tableName) {
        return pageMapper.selectFields(fields, tableName);
    }

    @Override
    public List<Map> selectFields2(String fields, String tableName, Wrapper<?> wrapper) {
        return pageMapper.selectFields2(fields, tableName, wrapper);
    }

    /**
     * ResultSet 转 List<Map<String, Object>>
     */
    private List<Map<String, Object>> convertList(ResultSet rs) {
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            ResultSetMetaData md = rs.getMetaData();
            int columnCount = md.getColumnCount();
            while (rs.next()) {
                Map<String, Object> rowData = new HashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    rowData.put(md.getColumnName(i), rs.getObject(i));
                }
                list.add(rowData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }
}
